package com.dinghui.pay.controller.alipay;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.dinghui.pay.common.ResponseResult;
import com.dinghui.pay.pojo.TbOrder;
import com.dinghui.pay.pojo.TbUser;
import com.dinghui.pay.pojo.param.LoginParam;
import com.dinghui.pay.pojo.param.PayOrderParam;
import com.dinghui.pay.pojo.param.UpdateNativeOrderStatusParam;
import com.dinghui.pay.pojo.param.UpdateOrderStatusParam;
import com.dinghui.pay.service.OrderService;
import com.dinghui.pay.service.UserService;
import com.dinghui.pay.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @version 1.0
 * @author: trt
 * @description:
 * @create: 2021-06-05 19:46
 */
// 网站 支付宝业务接口
@RestController
@RequestMapping("/api/alipay/web")
public class NativeController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private OrderService orderService;

    @Value("${alipay.app.app-id}")
    private String app_appId;

    @Value("${alipay.app.public-key}")
    private String app_publicKey;

    @Value("${alipay.app.private-key}")
    private String app_privateKey;

    @Value("${alipay.microApp.gateway}")
    private String gateway;

    /**
     * native 接口调用 :https://opendocs.alipay.com/open/203/105285
     */
    /**
     * native付款
     */
    @PostMapping("/nativePayOrder")
    public ResponseResult nativePayOrder(@RequestBody PayOrderParam param, @RequestHeader HashMap header) {
        String token = header.get("token").toString();
        Long userId = Long.parseLong(jwtUtils.getClaimByToken(token).getSubject());
        int orderId = param.getOrderId();
        TbUser user = new TbUser();
        user.setUserId(userId);
        long count = userService.getCount(user);
        //判断用户是否存在
        if (count == 0) {
            return ResponseResult.error("用户不存在");
        }

        //判断用户是否拥有这个订单，并且订单是未支付状态
        TbOrder order = new TbOrder();
        order.setUserId(userId.intValue());
        order.setId(orderId);
        order.setStatus(1);
        count = orderService.getCount(order);
        if (count == 0) {
            return ResponseResult.error("不是有效的订单");
        }

        // todo 验证购物券是否有效
        // todo 验证团购活动是否有效

        //查询订单详情信息
        order = new TbOrder();
        order.setId(orderId);
        order = orderService.getOne(order); //订单对象
        String amount = order.getAmount() + ""; //订单金额

        try {
            AlipayClient client = new DefaultAlipayClient(gateway, app_appId, app_privateKey, "json", "UTF-8", app_publicKey, "RSA2");
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            request.setReturnUrl("http://127.0.0.1:8848/mall/order.html");
            request.setNotifyUrl("http://www.demo.com");
            String subject = "Native付款";
            String body = "测试Native付款";
            request.setBizContent("{\"out_trade_no\":\"" + order.getCode() + "\","
                    + "\"total_amount\":\"" + amount + "\","
                    + "\"subject\":\"" + subject + "\","
                    + "\"body\":\"" + body + "\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            AlipayTradePagePayResponse response = client.pageExecute(request);
            String htmlCode = response.getBody();
            if (response.isSuccess()) {
                //更新本地商品订单信息，但是不更新商品订单状态
                order.setPaymentType(2); //支付类型
                order.setId(order.getId());  // 查询条件
                orderService.update(order);
                return ResponseResult.success("htmlCode", htmlCode);
            } else {
                return ResponseResult.error("支付订单创建失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("支付宝支付模块故障");
        }
    }


    // 更新商品订单状态
    @PostMapping("/updateNativeOrderStatus")
    public ResponseResult updateNativeOrderStatus(@RequestBody UpdateNativeOrderStatusParam param, @RequestHeader HashMap header) {
        String token = header.get("token").toString();
        int userId = Integer.parseInt(jwtUtils.getClaimByToken(token).getSubject());
        String code = param.getCode();
        TbOrder order = new TbOrder();
        order.setUserId(userId);
        order.setCode(code);
        int count = orderService.getCount(order);
        if (count == 0) {
            return ResponseResult.error("用户与订单不匹配");
        }

        try {
            AlipayClient client = new DefaultAlipayClient(
                    gateway,
                    app_appId,
                    app_privateKey,
                    "json",
                    "UTF-8",
                     app_publicKey,
                    "RSA2"
            );
            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            request.setBizContent("{" +
                    "\"out_trade_no\":\"" + code + "\"," +
                    "      \"query_options\":[" +
                    "        \"TRADE_SETTLE_INFO\"" +
                    "      ]" +
                    "  }");
            AlipayTradeQueryResponse response = client.execute(request);
            if (response.isSuccess()) {
                String tradeStatus = response.getTradeStatus();
                if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                    TbOrder tbOrder = new TbOrder();
                    tbOrder.setCode(code); // 查询条件
                    tbOrder.setStatus(2); // 修改值
                    tbOrder.setPaymentType(2); // 修改值
                    tbOrder.setPrepayId(response.getTradeNo()); // 修改值
                    orderService.updateOrderStatus(order);
                    return ResponseResult.success("订单状态已修改");
                } else {
                    return ResponseResult.success("订单状态未修改");
                }
            }
            return ResponseResult.success("订单状态未修改");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("查询支付订单失败");
        }
    }

}